<template>
  <div class="y-date-range-picker">
    <q-input
      v-model="displayRange"
      label="创建时间范围"
      outlined
      dense
      readonly
      clearable
      @clear="clearRange"
    >
      <template v-slot:prepend>
        <q-icon name="event" class="cursor-pointer">
          <q-popup-proxy cover transition-show="scale" transition-hide="scale">
            <div class="row q-pa-md">
              <div class="col">
                <q-date
                  v-model="startDate"
                  label="开始日期"
                  mask="YYYY-MM-DD"
                  :options="startDateOptions"
                />
              </div>
              <div class="col">
                <q-date
                  v-model="endDate"
                  label="结束日期"
                  mask="YYYY-MM-DD"
                  :options="endDateOptions"
                />
              </div>
            </div>
            <div class="row justify-end q-pa-sm">
              <q-btn label="确定" color="primary" @click="applyRange" flat v-close-popup />
            </div>
          </q-popup-proxy>
        </q-icon>
      </template>
    </q-input>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ from: null, to: null }),
  },
})

const emit = defineEmits(['update:modelValue'])

const startDate = ref(props.modelValue.from)
const endDate = ref(props.modelValue.to)

// 计算显示的日期范围文本
const displayRange = computed(() => {
  if (!startDate.value && !endDate.value) return null
  return `${startDate.value || ''} 至 ${endDate.value || ''}`
})

// 开始日期选项限制 - 不能晚于结束日期
const startDateOptions = (date) => {
  return !endDate.value || date <= endDate.value
}

// 结束日期选项限制 - 不能早于开始日期
const endDateOptions = (date) => {
  return !startDate.value || date >= startDate.value
}

// 应用日期范围
const applyRange = () => {
  emit('update:modelValue', {
    from: startDate.value,
    to: endDate.value,
  })
}

// 清空日期范围
const clearRange = () => {
  startDate.value = null
  endDate.value = null
  applyRange()
}

// 监听外部modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    startDate.value = newVal.from
    endDate.value = newVal.to
  },
  { deep: true },
)
</script>

<style lang="scss" scoped>
.y-date-range-picker {
  width: 100%;

  .q-date {
    width: 100%;
    min-width: 250px;
  }
}
</style>
